<template>
  <div class="common-layout linear-gradient">
    <el-container>
      <el-header style="height: 10vh">
        <div class="common-div-card headerSearchForm">
          <el-form :inline="true" :model="headerSearchForm" class="header-form">
            <el-form-item label="卷号">
              <el-input v-model="headerSearchForm.EXTID" placeholder="请输入卷号" />
            </el-form-item>
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="headerSearchForm.start"
                type="datetime"
                placeholder="开始时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="headerSearchForm.end"
                type="datetime"
                placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
              <el-button type="primary" @click="handleExport">导出</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-header>
      <el-main>
        <div class="table-container-main main-footer-padding" style="height: 34vh">
          <el-table
            :data="tableData"
            :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
          >
            <el-table-column prop="serialNumber" label="序号" fixed="left" width="50px">
              <template #default="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="EXTID" label="卷号" />
            <el-table-column prop="STEELGRADE" label="钢种" />
            <el-table-column prop="INMATTHK" label="入口厚度(mm)" />
            <el-table-column prop="INMATWIDTH" label="入口宽度(mm)" />
            <el-table-column prop="ELONGAIM" label="目标延伸率">
              <template #default="scope">
                <span>{{scope.row.ELONGAIM/10}}%</span>
              </template>
            </el-table-column>
            <el-table-column prop="ISLARGEROLLDIAMETER" width="80" label="大/小辊" />
            <el-table-column prop="rollingForceSet" label="轧制力设定值" />
            <el-table-column prop="LOWSPEEDROLLINGFORCE" label="轧制力设定实际值" />
            <el-table-column prop="LOWSPEEDWORKROLLBEND" label="工作辊弯辊力设定值" />
            <el-table-column prop="LOWSPEEDINTERMEDIATEROLLBEND" label="中间辊弯辊力设定值"></el-table-column>
            <el-table-column prop="WELDINGELONGRATE" label="过焊缝延伸率命中率" />
            <el-table-column prop="prodEndTime" label="生产结束时间" :formatter="formatDate" />
            <el-table-column label="详情" width="180" fixed="right" align="center">
              <template #default="scope">
                <button class="action-btn rate-btn" @click="openDialog(scope.row)">详情</button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[20, 30, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
      <el-footer height="100%">
        <div id="barChart" class="footer-bar-chart main-footer-padding"></div>
      </el-footer>
    </el-container>

    <!--弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle_id"
      class="layout-dialog"
      top="5vh"
      width="80%"
    >
      <div id="data-view">
        <div class="layout-search">
          <div class="layout-search">
            <dv-border-box-11 :title="'板形仪通道号(长度序列)'">
              <el-row style="width: 99%;">
                <el-col :span="24">
                  <div class="grid-content bg-purple">
                    <!--板形云图-->
                    <dv-border-box-10 style="width:100%;height:350px;">
                      <div id="app7" style="width:100%;height:350px;" />
                    </dv-border-box-10>
                  </div>
                </el-col>
              </el-row>
              <dv-border-box-11 :title="'延伸率追溯'">
                <dv-border-box-10>
                  <!--延伸率  -->
                  <div id="app_shifting_roll" style="width:99%;height:300px;" />
                </dv-border-box-10>
              </dv-border-box-11>
            </dv-border-box-11>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import {
  ref,
  reactive,
  computed,
  onMounted,
  onUnmounted,
  nextTick,
  defineComponent
} from "vue";
import { ElMessage } from "element-plus";
import "/@/views/RollingSimulation/rollingSimulationModelCommonStyle.less";
import { levelingMachineApi } from "/@/api/levelingmachine/index";
import { rollingSimulationApi } from "/@/api/RollingSimulation/index";
import { historyApi } from "/@/api/furnaceTempDynamicCtrl/history";
import * as echarts from "echarts";
import dayjs from "dayjs";

interface SearchForm {
  EXTID: string;
  start: string;
  end: string;
}

export default defineComponent({
  name: "DataDictionary",
  setup() {
    // 表单数据
    // 表单数据
    const headerSearchForm = reactive<SearchForm>({
      EXTID: "",
      start: "",
      end: ""
    });
    const dialogVisible = ref<boolean>(false);
    const dialogTitle = ref("");
    const dialogTitle_id = ref("");
    function formatDate(row: any, column: any, cellValue: any) {
      if (!cellValue) return '';
      return dayjs(cellValue).format('YYYY-MM-DD HH:MM:ss');
    }

    // 表格数据
    const tableData = ref([
      {
        EXTID: "M23132184C",
        STEELGRADE: "920",
        INMATTHK: "2.8",
        INMATWIDTH: "920",
        ELONGAIM: "0.6",
        ISLARGEROLLDIAMETER: "",
        LOWSPEEDROLLINGFORCE: "",
        CALSPMWELDFORCESET: "",
        LOWSPEEDWORKROLLBEND: "",
        LOWSPEEDINTERMEDIATEROLLBEND: ""
      }
    ]);

    const pdiMesInfo = ref<number[]>([]);
    let rememberA = <any>[];
    let rememberB = <any>[];
    let rememberC = <any>[];
    let rememberR = <any>[];
    let clickChanel = 13;
    const dialogVisible2 = ref(false);
    const dialogTitle2 = ref(""); //修改Y轴
    let sum = <any>1;
    const stretch_goals = ref([]);
    const echart = {
      max1: 30,
      min1: -10,
      max2: 30,
      min2: -30,
      // max3: 30,
      // min3: -30,
      max5: 30,
      min5: -30,
      max18: 25,
      min18: -25
    };
    let formData = "";

    const rollingProcedureTable = ref([
      {
        ITEM: "工作辊直径",
        UNIT: "mm",
        S1: "460",
        S2: "460",
        S3: "460",
        S4: "460",
        S5: "460"
      }
    ]);

    const simulationResultOutTable = ref([
      {
        ITEM: "速度",
        UNIT: "m/min",
        BEFORE: "/",
        STD1: "355",
        STD2: "515",
        STD3: "728",
        STD4: "975",
        STD5: "1273"
      },
      {
        ITEM: "速度",
        UNIT: "m/min",
        BEFORE: "/",
        STD1: "355",
        STD2: "515",
        STD3: "728",
        STD4: "975",
        STD5: "1273"
      },
      {
        ITEM: "速度",
        UNIT: "m/min",
        BEFORE: "/",
        STD1: "355",
        STD2: "515",
        STD3: "728",
        STD4: "975",
        STD5: "1273"
      },
      {
        ITEM: "速度",
        UNIT: "m/min",
        BEFORE: "/",
        STD1: "355",
        STD2: "515",
        STD3: "728",
        STD4: "975",
        STD5: "1273"
      },
      {
        ITEM: "速度",
        UNIT: "m/min",
        BEFORE: "/",
        STD1: "355",
        STD2: "515",
        STD3: "728",
        STD4: "975",
        STD5: "1273"
      },
      {
        ITEM: "速度",
        UNIT: "m/min",
        BEFORE: "/",
        STD1: "355",
        STD2: "515",
        STD3: "728",
        STD4: "975",
        STD5: "1273"
      },
      {
        ITEM: "速度",
        UNIT: "m/min",
        BEFORE: "/",
        STD1: "355",
        STD2: "515",
        STD3: "728",
        STD4: "975",
        STD5: "1273"
      },
      {
        ITEM: "速度",
        UNIT: "m/min",
        BEFORE: "/",
        STD1: "355",
        STD2: "515",
        STD3: "728",
        STD4: "975",
        STD5: "1273"
      }
    ]);

    const option = {
      xAxis: {
        splitLine: {
          //网格线
          show: false
        },
        axisLabel: {
          fontSize: 10 // 设置字体大小为14
        },
        data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
      },
      yAxis: {
        name: "轧制力/10kN",
        nameTextStyle: {
          fontSize: "8px",
          color: "#6d7882"
        },
        splitLine: {
          //网格线
          show: false
        },
        axisLabel: {
          fontSize: 10 // 设置字体大小为14
        }
      },
      series: [
        {
          type: "bar",
          data: [23, 24, 18, 25, 27, 28, 25]
        }
      ]
    };
    const option1 = {
      xAxis: {
        splitLine: {
          //网格线
          show: false
        },
        axisLabel: {
          fontSize: 10 // 设置字体大小为14
        },
        data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
      },
      yAxis: {
        name: "强力/10kN",
        nameTextStyle: {
          fontSize: "8px",
          color: "#6d7882"
        },
        splitLine: {
          //网格线
          show: false
        },
        axisLabel: {
          fontSize: 10 // 设置字体大小为14
        }
      },
      series: [
        {
          type: "bar",
          data: [23, 24, 18, 25, 27, 28, 25]
        }
      ]
    };
    const option2 = {
      xAxis: {
        splitLine: {
          //网格线
          show: false
        },
        axisLabel: {
          fontSize: 10 // 设置字体大小为14
        },
        data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
      },
      yAxis: {
        name: "速度[m/min]",
        nameTextStyle: {
          fontSize: "8px",
          color: "#6d7882"
        },
        splitLine: {
          //网格线
          show: false
        },
        axisLabel: {
          fontSize: 10 // 设置字体大小为14
        }
      },
      series: [
        {
          type: "bar",
          data: [23, 24, 18, 25, 27, 28, 25]
        }
      ]
    };
    const plateCurveData = ref([]);
    const option3 = {
      xAxis: {
        splitLine: {
          //网格线
          show: false
        },
        axisLabel: {
          fontSize: 10 // 设置字体大小为14
        },
        data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
      },
      yAxis: {
        name: "功率/kW",
        nameTextStyle: {
          fontSize: "8px",
          color: "#6d7882"
        },
        splitLine: {
          //网格线
          show: false
        },
        axisLabel: {
          fontSize: 10 // 设置字体大小为14
        }
      },
      series: [
        {
          type: "bar",
          data: [23, 24, 18, 25, 27, 28, 25]
        }
      ]
    };

    const dataSourceType = ref("");

    const dataSourceTypeOptions = ref([
      { label: "PLC", value: "PLC" },
      { label: "传感器", value: "传感器" },
      { label: "AI算法", value: "AI算法" },
      { label: "称重传感器", value: "称重传感器" },
      { label: "电池管理系统", value: "电池管理系统" }
    ]);

    // 分页数据
    const pagination = reactive({
      currentPage: 1,
      pageSize: 20,
      total: tableData.value.length
    });

    // 导出方法
    const handleExport = () => {
      // TODO: 实现导出逻辑
      ElMessage.info("导出功能待实现");
    };

    // 窗口大小变化处理
    const handleResize = () => {
      nextTick(() => {
        // 这里可以添加表格自适应高度的逻辑
      });
    };

    const handleCheck = (row: any) => {
      dialogVisible.value = true;
    };
    let toolbox = {
      iconStyle: {
        borderColor: "#fff"
      },
      feature: {
        dataView: {
          show: true,
          lang: ["数据视图", "关闭", "导出Excel"],
          //optionToContent为重画表格的函数
          optionToContent: function(opt: any) {
            //axisData是你想定义的表格第一列的数据，我这里设置为柱形图的x轴数据
            var axisData = opt.xAxis[0].data;
            //tAxis[0]为你想定义的表格第一行的数据
            var txisData = opt.series[0].data;
            // console.log(opt)
            var series = opt.series;
            //表头
            var tdHeads = '<td  style="padding: 0 10px"></td>';
            var tdBodys = "";
            var nameData = txisData;
            // console.log(nameData)
            for (var i = 0; i < nameData.length; i++) {
              tdHeads +=
                '<td style="padding: 0 10px">' + nameData[i] + "</ td >";
            }
            var table =
              '<table id="Mytable" border="1" class="table table-bordered table-striped table-hover" style="width:100%;text-align:center;color: #000;" ><tbody><tr>' +
              tdHeads +
              " </tr>";
            for (var i = 0, l = axisData.length; i < l; i++) {
              for (var j = 0; j < series.length; j++) {
                if (series[j].data != undefined) {
                  var temp = series[j].data[i];
                  if (temp != null && temp != undefined) {
                    tdBodys += "<td>" + temp + "</td>";
                  } else {
                    tdBodys += "<td></td>";
                  }
                }
              }
              table +=
                '<tr><td style="padding: 0 10px">' +
                axisData[i] +
                "</td>" +
                tdBodys +
                "</tr>";
              tdBodys = "";
            }
            table += "</tbody></table>";
            return table;
          },
          contentToOption: function(HTMLDomElement, opt) {
            let et = XLSX.utils.table_to_book(
              document.getElementById("Mytable")
            );
            let etout = XLSX.write(et, {
              bookType: "xlsx",
              bookSST: true,
              type: "array"
            });
            try {
              saveAs(
                new Blob([etout], {
                  type: "application/octet-stream"
                }),
                "echarts数据" + "-" + new Date().toLocaleString() + ".xlsx"
              );
            } catch (e) {}
            return etout;
          }
        },
        magicType: { show: true },
        restore: { show: true },
        saveAsImage: { show: true }
        // dataZoom: {show: true},
      }
    };

    function openDialog(row: any) {
      dialogVisible.value = true;
      dialogTitle_id.value = "酸轧出口卷号:" + row.EXTID;
      dialogTitle.value = "板形质量分析";
      formData = row.EXTID;

      // 清空之前的数据
      stretch_goals.value = [];
      plateCurveData.value = [];

      findAll4(row.EXTID, row);
      getElongationData(row.EXTID, row.ELONGAIM);
    }
    // 板形长度序列曲线
    async function findAll4(extid: any, row: any) {
      // 替换extid后四位为0000
      if (typeof extid === "string" && extid.length > 3) {
        extid = extid.slice(0, -3) + "000";
      }
      let params = [
        "tcm_shape_channe_0",
        "tcm_shape_channe_1",
        "tcm_shape_channe_2",
        "tcm_shape_channe_4",
        "tcm_shape_channe_5",
        "tcm_shape_channe_6",
        "tcm_shape_channe_7",
        "tcm_shape_channe_8",
        "tcm_shape_channe_9",
        "tcm_shape_channe_10",
        "tcm_shape_channe_11",
        "tcm_shape_channe_12",
        "tcm_shape_channe_13",
        "tcm_shape_channe_14",
        "tcm_shape_channe_15",
        "tcm_shape_channe_16",
        "tcm_shape_channe_17",
        "tcm_shape_channe_18",
        "tcm_shape_channe_19",
        "tcm_shape_channe_20",
        "tcm_shape_channe_21",
        "tcm_shape_channe_22",
        "tcm_shape_channe_23",
        "tcm_shape_channe_24",
        "tcm_shape_channe_25",
        "tcm_shape_channe_26",
        "tcm_shape_channe_27",
        "tcm_shape_channe_28",
        "tcm_shape_channe_29",
        "tcm_shape_channe_30",
        "tcm_shape_channe_31",
        "tcm_shape_channe_32",
        "tcm_shape_channe_33",
        "tcm_shape_channe_34",
        "tcm_shape_channe_35",
        "tcm_shape_channe_36",
        "tcm_shape_channe_37",
        "tcm_shape_channe_38",
        "tcm_shape_channe_39",
        "tcm_shape_channe_40",
        "tcm_shape_channe_41",
        "tcm_shape_channe_42",
        "tcm_shape_channe_43",
        "tcm_shape_channe_44",
        "tcm_shape_channe_45",
        "tcm_shape_channe_46",
        "tcm_shape_channe_47",
        "tcm_shape_channe_48",
        "tcm_shape_channe_49",
        "tcm_shape_channe_50",
        "tcm_shape_channe_51",
        "tcm_shape_channe_52",
        "tcm_shape_channe_53",
        "tcm_shape_channe_54",
        "tcm_shape_channe_55",
        "tcm_shape_channe_56",
        "tcm_shape_channe_57",
        "tcm_shape_channe_58",
        "tcm_shape_channe_59",
        "tcm_shape_channe_60",
        "tcm_shape_channe_61",
        "tcm_shape_channe_62",
        "tcm_shape_channe_63",
        "tcm_s5_strip_speed_act"
      ];

      const graphParam = {
        line: "TCM2280",
        extid: [extid],
        curve: params
      };
        const response = await historyApi.getgraphData(graphParam);
        //绘制2D板形图曲线-长度序列
        if (response.data.data.curve && response.data.data.curve[0] && Object.keys(response.data.data.curve[0]).length > 0) {
          let filteredObj = [];

          const newItem = Object.fromEntries(
            Object.entries(response.data.data.curve[0]).filter(([key, value]) => {
              if (Array.isArray(value)) {
                value.some(num => num !== 0);
              }
              return value;
            })
          );
          filteredObj.push({ ...newItem });

          console.log("filteredObj" + filteredObj);

          echart_test7(filteredObj);
          plateCurveData.value = response.data.data.curve[0];
        } else {
          plateCurveData.value = [];
          echarts_no("app7");
        }
    }
    // 无数据时：展示暂无数据
    function echarts_no(e: any, height = 400) {
      console.log("e" + e);
      const dom = document.getElementById(e);
      if (dom != null) {
        dom.innerHTML = "暂无数据";
        dom.style.cssText =
          "text-align:center; color: #999; border: none;line-height:" +
          height +
          "px";
        dom.removeAttribute("_echarts_instance_");
      }
    }
    function echart_test7(datas10: any) {
      var need_x11 = [];
      console.log(datas10);
      for (var i = 0; i < datas10[0].tcm_shape_channe_11.length; i++) {
        need_x11.push(i + 1);
      }
      let res: any = [];
      let max = 0; //这个值用于计算两边通道有多个全为0的通道个数，最后用来补齐拟合曲线的个数
      Object.entries(datas10[0]).forEach(([key, value]) => {
        const macthReq = /tcm_shape_channe_(\d+)$/.exec(key);
        if (!macthReq || value.every(i => i === 0)) return; //去掉所有通道数组全为0的通道
        const index = Number(macthReq[1]); //根据曲线名称例如channel_26,用正则获取通道号数字
        max = Math.max(max, index); //取最大的且通道数据不全为0的通道号

        value.forEach((v: any, i: any) => {
          res.push([i, index - 1, v]); //组装板形图的数据
          // 第一个元素代表X轴、第二个Y轴、第三个是值
        });
      });
      // console.log(res)
      // 取第一米的各通道数据，用于默认显示第一米板形截面图
      let Tuglie = [];
      for (var x = 0; x < res.length; x++) {
        if (res[x]["0"] == 1) {
          Tuglie.push(res[x]);
        }
      }
      // 将第一米界面的数据处理，排序过后从二维数组中，取出对应板形值，放置在一元数组，用来绘制截面图
      let list: any = [];
      // console.log(this.Tuglie.sort((a, b) => a[1] - b[1]))
      list = Tuglie.sort((a, b) => a[1] - b[1])
        .map(item => {
          return item[2];
        })
        // .reverse()
        .join(",");
      var myChart = echarts.init(document.getElementById("app7")); //将配置注入到html中定义的容器
      // prettier-ignore
      let days = [
    'c_0', 'c_1',
    'c_2', 'c_3', 'c_4', 'c_5','c_6', 'c_7', 'c_8', 'c_9','c_10',
    'c_11', 'c_12', 'c_13', 'c_14','c_15', 'c_16', 'c_17', 'c_18','c_19',
    'c_20', 'c_21', 'c_22', 'c_23','c_24','c_25','c_26','c_27','c_28','c_29',
    'c_30','c_31','c_32','c_33','c_34','c_35','c_36','c_37','c_38','c_39','c_40',
    'c_41','c_42','c_43','c_44','c_45','c_46','c_47','c_48','c_49','c_50','c_51',
    'c_52','c_53','c_54','c_55','c_56','c_57','c_58','c_59','c_60','c_61','c_62','c_63'
  ];
      //计算单侧边部通道需要补0的个数
      let listMxsMin = days.length - max;
      let a1: any = [];
      for (var i = 0; i < listMxsMin; i++) {
        a1.push("0.00");
      }
      //拟合方程开始
      let newX = list.split(",");
      let zeroPoint = parseInt(newX.length / 2); //取所有通道中间点
      let leftX = [];
      let rightX = [];
      //存放X正半轴
      for (let i = 0; i < zeroPoint; i++) {
        leftX.push(parseFloat(((2 * i + 1) / newX.length).toFixed(2)));
      }
      //存放X负半轴
      for (let i = 1; i <= zeroPoint; i++) {
        rightX.push(parseFloat(((-2 * i + 1) / newX.length).toFixed(2)));
      }
      //拼接成一个完整的X轴
      let allXaxis = rightX.reverse().concat(leftX);
      let allYaxis = [];
      allXaxis.forEach((item, index) => {
        // 计算a*x平方+b*x+c
        allYaxis.push(
          parseFloat(
            rememberA[0] * Math.pow(item, 2) * 1 +
              rememberB[0] * item * 1 +
              rememberC[0] * 1
          ).toFixed(2) * 1
        );
      });
      // 最后补齐两侧通道为0的通道的数据，保证元素个数与通道号一致
      for (let i = 0; i < listMxsMin; i++) {
        allYaxis.push("");
        allYaxis.unshift("");
      }

      let titleA = rememberA[0];
      let titleB = rememberB[0];
      let titleC = rememberC[0];
      let titleR = rememberR[0];
      // 取第一米的板形截面数据，并按照升序排列，保证通道后由小到大
      var listST = [];
      listST = res
        .filter(i => i[0] === 1)
        .sort((a: any, b: any) => a[1] - b[1])
        .map(i => i[2]);
      // 补齐板形截面柱状图两侧通道个数，保证元素个数与通道号一致
      var lnewaWa = a1.join() + "," + listST + "," + a1.join();
      find_singleChanel(formData, clickChanel);
      var option = {
        title: {
          text: "",
          textStyle: {
            color: "#222", // 深色
            fontStyle: "normal",
            fontWeight: "bold",
            fontFamily: "Microsoft YaHei, Segoe UI, Arial, sans-serif",
            fontSize: 18
          }
        },
        tooltip: {
          position: "top"
        },
        grid: {
          left: "3%",
          right: "6%",
          containLabel: true
        },
        xAxis: {
          axisLine: {
            lineStyle: {
              color: "#888",
              width: 1
            }
          },
          name: "(m)",
          nameTextStyle: {
            fontSize: 15,
            padding: [0, 0, 0, -10],
            color: "#333"
          },
          type: "category",
          data: need_x11,
          axisLabel: {
            color: "#333",
            fontSize: 13,
            fontWeight: "bold"
          }
        },
        yAxis: {
          axisLine: {
            lineStyle: {
              color: "#888",
              width: 1
            }
          },
          nameTextStyle: {
            fontSize: 10,
            padding: [0, 0, 0, -10],
            color: "#333"
          },
          type: "category",
          data: days,
          axisLabel: {
            color: "#333",
            fontSize: 13,
            fontWeight: "bold"
          }
        },
        legend: {
          left: "center",
          textStyle: {
            fontSize: 16,
            color: "#222"
          }
        },
        visualMap: {
          min: -25,
          max: 25,
          calculable: true,
          orient: "vertical",
          left: "right",
          top: "center",
          realtime: false,
          textStyle: {
            color: "#222"
          },
          inRange: {
            color: [
              "RGB(0,10,255)",
              "RGB(0,150,255)",
              "RGB(0,199,255)",
              "#11fff9",
              "RGB(0,255,0)",
              "#FFF500",
              "RGB(255,230,0)",
              "RGB(249, 102, 72)",
              "RGB(255,0,0)"
            ]
          }
        },
        series: [
          {
            pointSize: 10,
            type: "heatmap",
            data: res.sort((a: any, b: any) => a[0] - b[0])
          }
        ]
      };
      //使用刚指定的配置项和数据显示图表。
      // myChart.setOption(option, true)
      //清空画布，防止缓存
      myChart.clear();
      //使用刚指定的配置项和数据显示图表。mouseover
      myChart.setOption(option, true);
      myChart.getZr().on("click", params => {
        /* 通过获取echarts上面点击的区域是在第几格，根据索引来判断数据 */
        let pointInPixel = [params.offsetX, params.offsetY];
        var lattice: any = "";
        if (myChart.containPixel("grid", pointInPixel)) {
          var xIndex: any = myChart.convertFromPixel(
            { seriesIndex: 0 },
            pointInPixel
          )[0];
          var yIndex = myChart.convertFromPixel(
            { seriesIndex: 0 },
            pointInPixel
          )[1];
          lattice = xIndex;
          clickChanel = yIndex;
          find_singleChanel(formData, clickChanel);
        }
        Tuglie = [];
        for (var x = 0; x < res.length; x++) {
          if (res[x]["0"] == xIndex) {
            Tuglie.push(res[x]);
          }
        }
        var list: any = [];
        // console.log(this.Tuglie.sort((a, b) => a[1] - b[1]))
        list = Tuglie.sort((a, b) => a[1] - b[1])
          .map(item => {
            return item[2];
          })
          // .reverse()
          .join(",");
        //方程开始
        let newX = list.split(",");
        let zeroPoint = parseInt(newX.length / 2); //取中间点
        let leftX = [];
        let rightX = [];
        //存放X正半轴
        for (let i = 0; i < zeroPoint; i++) {
          leftX.push(parseFloat(((2 * i + 1) / newX.length).toFixed(2)));
        }
        //存放X负半轴
        for (let i = 1; i <= zeroPoint; i++) {
          rightX.push(parseFloat(((-2 * i + 1) / newX.length).toFixed(2)));
        }
        //拼接成一个完整的X轴
        let allXaxis = rightX.reverse().concat(leftX);
        let allYaxis = [];
        allXaxis.forEach((item, index) => {
          // a*x平方+b*x+c
          allYaxis.push(
            parseFloat(
              rememberA[lattice - 1] * Math.pow(item, 2) * 1 +
                rememberB[lattice - 1] * item * 1 +
                rememberC[lattice - 1] * 1
            ).toFixed(2) * 1
          );
        });
        //补齐数组
        for (let i = 0; i < listMxsMin; i++) {
          allYaxis.push("");
          allYaxis.unshift("");
        }
      });
    }
    // 板形长度序列曲线
    async function find_singleChanel(extid: any, chanel: any) {
      if (chanel <= 0 || chanel > 26) {
        return;
      }
      let chanel_f = [];
      chanel_f.push("tcm_shape_channe_" + chanel);
      let str = "tcm_shape_channe_" + chanel;

      const graphParam = {
        line: "TCM2280",
        extid: [extid],
        curve: chanel_f
      };
      let res = await historyApi.getgraphData(graphParam);
      //绘制2D板形图曲线-长度序列
      if (
        res.data.data.curve && res.data.data.curve[0] && Object.keys(res.data.data.curve[0]).length > 0
      ) {
        echart_singleChanel(res.data.data.curve[0][str], str, "app_chanel");
      } else {
        echarts_no("app_chanel");
      }
    }
    function echart_singleChanel(data: any, title: any, id: any) {
      var need_x11 = [];
      var need_y11 = [];
      need_y11 = data;
      for (let i = 0; i <= data.length; i++) {
        need_x11.push(i + 1);
      }
      toolbox.feature.myTool = {
        show: true, //是否显示
        title: "定义y轴", //鼠标悬空的提示文字
        icon:
          "path://M659.77002 969.890638 363.679441 969.890638 363.679441 644.667555 33.604864 76.752058l325.225129 0 155.319461 300.952306L669.480172 76.752058 989.844597 76.752058 659.77002 639.812991 659.77002 969.890638z", //这个是阿里icon svg 后 b的全部字符串
        onclick: () => {
          sum = 18;
          dialogVisible2.value = true;
          dialogTitle2.value = "定义Y轴刻度范围";
        }
      };
      var myChart = echarts.init(document.getElementById(id)); //将配置注入到html中定义的容器
      var option = {
        title: {
          text: title,
          textStyle: {
            fontSize: 14,
            color: "#ffffff"
          }
        },
        color: "yellow",
        // legend: {
        //   x: 'center', //可设定图例在左、右、居
        //   textStyle: {
        //     // fontWeight: 'bolder', 字体加粗
        //     fontSize: 12,
        //     color: '#fff'
        //   },
        //   icon: 'roundRect'
        // },
        toolbox: toolbox,
        tooltip: {
          trigger: "axis"
        },
        //表头
        grid: {
          left: "3%",
          right: "5%",
          top: "15%",
          bottom: "18%",
          containLabel: true
        },
        xAxis: {
          axisLine: {
            lineStyle: {
              color: "#ffffff"
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: "dotted"
            }
          },
          // intercal: 50,
          nameTextStyle: {
            fontSize: 12,
            // padding: [0, -50, 100, 0],
            color: "#ffffff"
          },
          name: "(m)",
          type: "category",
          data: need_x11
        },
        yAxis: [
          {
            scale: true, //纵坐标自适应
            axisLine: {
              lineStyle: {
                color: "#ffffff"
              }
            },
            min: echart.min18,
            max: echart.max18,
            type: "value",
            name: "",
            axisLabel: {
              formatter: "{value}",
              textStyle: {
                color: "#ffffff"
              }
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: "dotted"
              }
            }
          }
        ],
        series: [
          {
            name: "",
            type: "line",
            data: need_y11.map(value => value / 20)
          }
        ]
      };
      myChart.clear();
      myChart.setOption(option);
    }
    // 获取表格数据
    const formatCompactDateTime = (value: string) => {
      if (!value) return "";
      const parsed = dayjs(value);
      return parsed.isValid() ? parsed.format("YYYYMMDDHHmmss") : value;
    };

    const fetchTableData = async () => {
      try {
        const params: any = {
          pageIndex: String(pagination.currentPage),
          pageSize: String(pagination.pageSize)
        };

        const searchParams: any = {
          pageIndex: String(pagination.currentPage),
          pageSize: String(pagination.pageSize),
          start: formatCompactDateTime(headerSearchForm.start),
          end: formatCompactDateTime(headerSearchForm.end),
          extid: headerSearchForm.EXTID
        };

        // 移除未定义的参数，避免发送空字符串
        Object.keys(params).forEach(key => {
          if (params[key as keyof typeof params] === undefined) {
            delete params[key as keyof typeof params];
          }
        });

        console.log("Fetching data with params:", params);
        let lowSpeedIntermeadiateRollBend = 0;
        let param = {
          name: "CAL1630_RealData"
        };
        rollingSimulationApi.rest(param).then(ress => {
          console.log(ress.data["G401_554NI"]);
          lowSpeedIntermeadiateRollBend = ress.data["G401_554NI"];
        });
        const response = await levelingMachineApi.findHistorySetValueByPage(
          searchParams
        );
        console.log("API Response:", response);

        // Correctly access data from response.data if 'response' is an AxiosResponse
        const responseData = response.data;

        if (
          responseData &&
          responseData.data &&
          Array.isArray(responseData.data.records)
        ) {
          console.log(lowSpeedIntermeadiateRollBend);
          tableData.value = responseData.data.records.map((item: any) => ({
            EXTID: item.extid,
            STEELGRADE: item.steelgrade,
            INMATTHK: item.inMatThk,
            INMATWIDTH: item.inMatWidth,
            ELONGAIM: item.elongAim,
            ISLARGEROLLDIAMETER: item.isLargeRollDiameter == 0 ? "否" : "是",
            LOWSPEEDROLLINGFORCE: numberFormat1(item.lowSpeedRollingForce),
            LOWSPEEDWORKROLLBEND: numberFormat1(item.lowSpeedWorkRollBend),
            LOWSPEEDINTERMEDIATEROLLBEND: item.lowSpeedIntermediateRollBend,
            WELDINGELONGRATE: numberFormat1(item.weldingElongRate),
            WEILDINGROLLINGFORCEACT: numberFormat1(
              item.weildingRollingForceAct
            ),
            ...item // Keep other original fields if needed for detail view
          }));
          console.log(tableData.value);
          pagination.total =
            responseData.count || responseData.data.records.length; // Use responseData.count for total
          ElMessage.success(responseData.msg || "查询成功");
        } else {
          ElMessage.info(
            responseData?.msg ||
              (response as any)?.msg ||
              "未查询到数据或响应格式不正确"
          );
          tableData.value = [];
          pagination.total = 0;
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        // Try to get error message from error.response.data.msg or error.data.msg
        const errorMessage =
          error.response?.data?.msg ||
          error.data?.msg ||
          error.msg ||
          error.message ||
          "获取数据失败";
        ElMessage.error(errorMessage);
        tableData.value = [];
        pagination.total = 0;
      }
    };

    const findHistoryFlatnessPercentage = async () => {
      try {
        const params: any = {};
        const response = await levelingMachineApi.findHistoryFlatnessPercentage(
          params
        );
        if (response && response.data) {
          const responsePayload = response.data.data;
          pdiMesInfo.value = [
            responsePayload.countLessThan10,
            responsePayload.countLessThan20,
            responsePayload.countLessThan30,
            responsePayload.countLessThan40,
            responsePayload.countLessThan50,
            responsePayload.countLessThan60,
            responsePayload.countLessThan70,
            responsePayload.countLessThan80,
            responsePayload.countLessThan90,
            responsePayload.countLessThan100,
            responsePayload.countLessThanTotal
          ];
          renderChart();
          ElMessage.success(responsePayload.msg || "查询成功");
        } else {
          ElMessage.info(response?.data?.msg || "未查询到数据或响应格式不正确");
          pdiMesInfo.value = [];
          pagination.total = 0;
          renderChart();
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        ElMessage.error(
          error.response?.data?.msg || error.message || "获取数据失败"
        );
        pdiMesInfo.value = [];
        pagination.total = 0;
        renderChart();
      }
    };

    // 渲染柱状图
    function renderChart() {
      const chartDom = document.getElementById("barChart");
      if (chartDom) {
        const myChart = echarts.init(chartDom);
        const option = {
          title: {
            text: "偏差分布柱状图",
            left: "center"
          },
          tooltip: {},
          xAxis: {
            data: [
              "<10%",
              "10%-20%",
              "20%-30%",
              "30%-40%",
              "40%-50%",
              "50%-60%",
              "60%-70%",
              "70%-80%",
              "80%-90%",
              "90%-100%",
              ">100%"
            ]
          },
          yAxis: {
            name: "卷数"
          },
          series: [
            {
              name: "",
              type: "bar",
              data: pdiMesInfo.value
            }
          ]
        };
        myChart.setOption(option);
      }
    }

    const numberFormat1 = (number: any) => {
      return number == undefined ? "0" : Number(parseFloat(number).toFixed(0));
    };

    // 查询方法
    const handleSearch = () => {
      pagination.currentPage = 1;
      fetchTableData();
    };

    // 重置方法
    const handleReset = () => {
      (Object.keys(headerSearchForm) as Array<keyof SearchForm>).forEach(
        key => {
          headerSearchForm[key] = "";
        }
      );
      handleSearch();
    };

    // 删除方法
    const handleDelete = (row: any) => {
      // 这里添加删除逻辑
      console.log("删除", row);
    };

    // 分页大小变化
    const handleSizeChange = (val: number) => {
      pagination.pageSize = val;
      fetchTableData();
    };

    // 页码变化
    const handleCurrentChange = (val: number) => {
      pagination.currentPage = val;
      fetchTableData();
    };

    // 生命周期钩子
    onMounted(() => {
      fetchTableData();
      findHistoryFlatnessPercentage();
      window.addEventListener("resize", handleResize);
      nextTick(() => {
        const chartDom = document.getElementById("barChart");
        if (chartDom) {
          const myChart = echarts.init(chartDom);
          const option = {
            title: {
              text: "偏差分布柱状图",
              left: "center"
            },
            tooltip: {},
            // legend: {
            //   data: ['AI_SET vs LOW_SPEED_ROLLING_FORCE', 'WEILDING_ROLLING_FORCE_ACT vs LOW_SPEED_ROLLING_FORCE'],
            //   top: 30
            // },
            xAxis: {
              data: [
                "<10%",
                "10%-20%",
                "20%-30%",
                "30%-40%",
                "40%-50%",
                "50%-60%",
                "60%-70%",
                "70%-80%",
                "80%-90%",
                "90%-100%",
                ">100%"
              ]
            },
            yAxis: {
              name: "卷数"
            },
            series: [
              {
                name: "",
                type: "bar",
                data: pdiMesInfo.value
              }
            ]
          };
          myChart.setOption(option);
        }
      });
    });

    async function getElongationData(seed: any, targetElongation: any) {
      try {
        let params = ["cal_spm_elong_act"];

        const graphParam = {
          line: "CAL1630",
          extid: [seed],
          curve: params
        };

        console.log("获取图表数据参数:", graphParam);
        const response = await historyApi.getgraphData(graphParam);
        console.log("图表数据响应:", response);

        if (
          response &&
          response.data &&
          response.data.data &&
          response.data.data.curve &&
          response.data.data.curve[0] &&
          Object.keys(response.data.data.curve[0]).length > 0
        ) {
          const curveData = response.data.data.curve[0];
          // 确保延伸率数据保留2位小数
          const rawData = curveData["cal_spm_elong_act"] || [];
          stretch_goals.value = rawData.map((value: any) => parseFloat(parseFloat(value).toFixed(2)));
          
          // 绘制延伸率曲线
          nextTick(() => {
            renderElongationChart(targetElongation);
          });
        } else {
          console.warn("图表数据格式不正确或为空");
          stretch_goals.value = [];
          // 显示无数据状态
          nextTick(() => {
            renderElongationChart(targetElongation);
          });
        }
      } catch (error) {
        console.error("获取图表数据失败:", error);
        stretch_goals.value = [];
        // 显示无数据状态
        nextTick(() => {
          renderElongationChart(targetElongation);
        });
      }
    }

        // 绘制延伸率曲线
    function renderElongationChart(targetElongation: any) {
      const chartDom = document.getElementById("app_shifting_roll");
      if (chartDom) {
        const myChart = echarts.init(chartDom);
        
        // 生成横坐标数据，1个点为1米
        const xAxisData = [];
        if (stretch_goals.value && stretch_goals.value.length > 0) {
          for (let i = 0; i < stretch_goals.value.length; i++) {
            xAxisData.push(i + 1); // 从1米开始
          }
        }
        
        // 计算目标延伸率（转换为百分比）
        const targetElongationPercent = parseFloat((targetElongation / 10).toFixed(2)); // 假设目标延伸率需要除以10转换为百分比
        const upperLimit = parseFloat((targetElongationPercent + 0.1).toFixed(2)); // 上限
        const lowerLimit = parseFloat((targetElongationPercent - 0.1).toFixed(2)); // 下限
        
        // 生成上下限数据
        const upperLimitData = new Array(stretch_goals.value.length).fill(upperLimit);
        const lowerLimitData = new Array(stretch_goals.value.length).fill(lowerLimit);
        const targetLineData = new Array(stretch_goals.value.length).fill(targetElongationPercent);
        
        const option = {
          title: {
            text: "",
            textStyle: {
              color: "#222",
              fontFamily: "Microsoft YaHei, Segoe UI, Arial, sans-serif",
              fontSize: 16,
              fontWeight: "bold"
            }
          },
          tooltip: {
            trigger: "axis",
            backgroundColor: "rgba(255, 255, 255, 0.9)",
            borderColor: "#2c69e8",
            borderWidth: 1,
            textStyle: {
              color: "#333"
            },
            formatter: function(params: any) {
              let result = `位置: ${params[0].axisValue}米<br/>`;
              params.forEach((param: any) => {
                if (param.seriesName === "延伸率") {
                  result += `延伸率: ${parseFloat(param.value).toFixed(2)}%<br/>`;
                } else if (param.seriesName === "目标值") {
                  result += `目标值: ${parseFloat(param.value).toFixed(2)}%<br/>`;
                } else if (param.seriesName === "上限") {
                  result += `上限: ${parseFloat(param.value).toFixed(2)}%<br/>`;
                } else if (param.seriesName === "下限") {
                  result += `下限: ${parseFloat(param.value).toFixed(2)}%<br/>`;
                }
              });
              return result;
            }
          },
          legend: {
            data: ["延伸率", "上限", "下限"],
            top: "18%",
            textStyle: {
              color: "#333",
              fontSize: 12
            }
          },
          grid: {
            left: "3%",
            right: "6%",
            bottom: "3%",
            top: "25%",
            containLabel: true
          },
          xAxis: {
            type: "category",
            data: xAxisData,
            name: "位置 (m)",
            nameTextStyle: {
              color: "#333",
              fontSize: 12,
              fontWeight: "bold"
            },
            axisLine: {
              lineStyle: {
                color: "#888"
              }
            },
            axisLabel: {
              color: "#333",
              fontSize: 12,
              fontWeight: "bold"
            },
            splitLine: {
              show: false
            }
          },
          yAxis: {
            type: "value",
            name: "延伸率 (%)",
            nameTextStyle: {
              color: "#333",
              fontSize: 12,
              fontWeight: "bold"
            },
            axisLine: {
              lineStyle: {
                color: "#888"
              }
            },
            axisLabel: {
              color: "#333",
              fontSize: 12,
              fontWeight: "bold"
            },
            splitLine: {
              lineStyle: {
                type: "dashed",
                color: "#ddd"
              }
            }
          },
          series: [
            {
              name: "延伸率",
              type: "line",
              data: stretch_goals.value,
              smooth: true,
              symbol: "circle",
              symbolSize: 4,
              lineStyle: {
                color: "#2c69e8",
                width: 3
              },
              itemStyle: {
                color: "#2c69e8",
                borderColor: "#fff",
                borderWidth: 2
              },
              areaStyle: {
                color: {
                  type: "linear",
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: "rgba(44, 105, 232, 0.4)"
                    },
                    {
                      offset: 1,
                      color: "rgba(44, 105, 232, 0.05)"
                    }
                  ]
                }
              }
            },
            {
              name: "上限",
              type: "line",
              data: upperLimitData,
              smooth: false,
              symbol: "none",
              lineStyle: {
                color: "#1890ff",
                width: 2,
                type: "dashed"
              },
              itemStyle: {
                color: "#1890ff"
              }
            },
            {
              name: "下限",
              type: "line",
              data: lowerLimitData,
              smooth: false,
              symbol: "none",
              lineStyle: {
                color: "#52c41a",
                width: 2,
                type: "dashed"
              },
              itemStyle: {
                color: "#52c41a"
              }
            }
          ]
        };
        
        // 如果没有数据，显示无数据状态
        if (!stretch_goals.value || stretch_goals.value.length === 0) {
          chartDom.innerHTML = "暂无延伸率数据";
          chartDom.style.cssText = "text-align:center; color: #999; border: none; line-height: 300px; font-size: 16px;";
          chartDom.removeAttribute("_echarts_instance_");
          return;
        }
        
        myChart.setOption(option);
        
        // 监听窗口大小变化，重新调整图表大小
        window.addEventListener("resize", () => {
          myChart.resize();
        });
      }
    }

    onUnmounted(() => {
      stretch_goals.value = [];
      window.removeEventListener("resize", handleResize);
    });



    const form = reactive({
      name: "",
      region: "",
      date1: "",
      date2: "",
      delivery: false,
      type: [],
      resource: "",
      desc: ""
    });

    return {
      headerSearchForm,
      tableData,
      pagination,
      handleSearch,
      handleReset,
      handleExport,
      handleCheck,
      handleDelete,
      handleSizeChange,
      handleCurrentChange,
      dataSourceTypeOptions,
      dataSourceType,
      dialogVisible,
      dialogTitle_id,
      form,
      rollingProcedureTable,
      simulationResultOutTable,
      option,
      option1,
      option2,
      option3,
      openDialog,
      formatDate
    };
  }
});
</script>
<style scoped lang="less">
@border-radius: 8px;
@primary-color: #2c69e8;
@box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
@box-shadow-hover: 0 8px 32px rgba(0, 0, 0, 0.12);
@border: 1px solid #dcdfe6;

.common-div-card {
  box-shadow: @box-shadow;
  transition: 0.3s;
  border-radius: @border-radius;
  border: @border;

  // 悬停状态
  &:hover {
    box-shadow: @box-shadow-hover;
  }
}
.msg-title {
  top: -4vh;
  left: 39.5vw;
  background-image: -webkit-linear-gradient(left, #0072ff, #00eaff, #01aaff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-size: 2vh;
  font-weight: bolder;
  width: 10vw;
}

:deep(.aprd-search-form .el-input--small .el-input__inner),
:deep(.aprd-search-form .el-select--small .el-select__input-wrapper input),
:deep(.aprd-search-form .el-date-editor--small .el-range-input),
:deep(.aprd-search-form .el-date-editor--small .el-range-separator) {
  font-size: 12px !important;
}

:deep(.aprd-search-form .el-select--small) {
  width: 150px;
}

:deep(.aprd-search-form .el-form-item__label) {
  font-size: 12px;
  line-height: 28px;
  color: #606266;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 3px;
}

:deep(.el-table) {
  font-size: 12px;
}

::v-deep .el-table--enable-row-transition .el-table__body td {
  padding-top: 4px;
  padding-bottom: 4px;
}

::v-deep .el-table .el-table__cell {
  padding-top: 4px !important;
}

.headerSearchForm {
  background-color: #fff;
  padding: 20px;
  margin-top: 1vh;

  .header-form {
    display: flex;
    gap: 20px;
  }
}

.footer-bar-chart {
  width: 100%;
  height: 300px;
  background: #fff;
  margin: 0 auto;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  border-radius: 8px;
  padding: 16px 0 0 0;
}

.action-btn {
  padding: 3px 8px;
  font-size: 12px;
  border: none;
  border-radius: 3px;
  margin: 0 2px;
  cursor: pointer;
  color: #000;
}
.rate-btn {
  background-color: #e6a23c;
}

.layout-search .el-form .el-form-item {
  margin-bottom: 12px;
}

// 弹窗样式优化
:deep(.layout-dialog .el-dialog__header) {
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 18px 24px 12px 24px;
  border-radius: 10px 10px 0 0;
}

:deep(.layout-dialog .el-dialog__title) {
  font-size: 20px;
  font-weight: bold;
  color: #222;
}

:deep(.layout-dialog .el-dialog__body) {
  padding: 24px;
  background: #fff;
  border-radius: 0 0 10px 10px;
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.layout-dialog .el-dialog) {
  border-radius: 10px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.18);
  background: #fff;
  font-family: "Microsoft YaHei", "Segoe UI", Arial, sans-serif;
  color: #222;
}

:deep(.layout-dialog .el-dialog__close) {
  font-size: 22px;
  color: #888;
  top: 18px;
  right: 18px;
}

:deep(.layout-dialog .el-dialog__body)::-webkit-scrollbar {
  width: 8px;
}

:deep(.layout-dialog .el-dialog__body)::-webkit-scrollbar-thumb {
  background: #e0e0e0;
  border-radius: 4px;
}
</style>